package com.example.nettyrpcdemo.core;

import com.google.protobuf.GeneratedMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import lombok.AllArgsConstructor;
import lombok.Data;
import tools.MessageManager;

/**
 * rpc请求上下文
 */
@Data
@AllArgsConstructor
public class GameRpcMsgContext {

    private Channel channel;
    // 对于call消息才有值
    private long callbackId;

    private GeneratedMessage msg;

    @SuppressWarnings("all")
    public <T> T getMsg() {
        return (T) msg;
    }

    public void sendAnswerMsg(GeneratedMessage msg) {
        int msgId = MessageManager.getMsgIdByMsgClazz(msg.getClass());

        byte[] bytes = msg.toByteArray();

        // 4head 4msgid + 8seqId + body
        int len = 4 + 4 + 8 + bytes.length;
        ByteBuf byteBuf = channel.alloc().buffer(len);
        byteBuf.writeInt(len);
        byteBuf.writeInt(msgId);
        byteBuf.writeLong(callbackId); // 客户端根据这个执行回调函数
        byteBuf.writeBytes(bytes);

        channel.writeAndFlush(byteBuf);
    }
}
